package com.suyx.job.service.impl;


import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.suyx.job.dao.RoleInfoRepository;
import com.suyx.job.dao.TuInfoLogRepository;
import com.suyx.job.entity.DeviceInfo;
import com.suyx.job.entity.Page;
import com.suyx.job.entity.RoleInfo;
import com.suyx.job.entity.TuInfoLog;
import com.suyx.job.service.IRoleInfoService;
import com.suyx.job.service.base.impl.MyServiceImpl;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/18 0018 11:50
 * @Description:
 */
@Slf4j
@Service
public class RoleInfoServiceImpl extends MyServiceImpl<RoleInfo,Integer> implements IRoleInfoService {
	
	private RoleInfoRepository roleInfoRepository;

    @Autowired
    public RoleInfoServiceImpl(RoleInfoRepository repository) {
        super(repository);
        this.roleInfoRepository = repository;
    }

	@Override
	public Page findRolePage(RoleInfo roleInfo, Integer page, Integer limit) {
		return new Page(
				roleInfoRepository.findAll((Root<RoleInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if(!StringUtils.isEmpty(roleInfo.getRoleName())){
                        predicates.add(cb.like(root.get("roleName").as(String.class), "%"+roleInfo.getRoleName() + "%"));
                    }
                    if(!StringUtils.isEmpty(roleInfo.getRoleSect())){
                        predicates.add(cb.equal(root.get("roleSect").as(String.class), roleInfo.getRoleSect()));
                    }
                    if(!StringUtils.isEmpty(roleInfo.getStatus())){
                        predicates.add(cb.equal(root.get("status").as(String.class), roleInfo.getStatus()));
                    }
                    if(!StringUtils.isEmpty(roleInfo.getDevice())){
                        predicates.add(cb.equal(root.get("device").as(String.class), roleInfo.getDevice()));
                    }
                    return  query.where(predicates.toArray(new Predicate[0]))
                    		.orderBy(cb.asc(root.get("roleId").as(Integer.class))).getRestriction();
                }, PageRequest.of(page,limit)));
	}
}
